import { defineStore } from 'pinia';
import { getToken, setToken, clearToken } from '@/utils';
import { login, logout } from '@/api/user';
import { useAsyncRoutes } from '../asyncRoutes';
import type { RootObject } from '@/api/types/rootObject';
import type { LoginData, LogoutData } from '@/api/types/user';
export const useLoginInfo = defineStore('user', {
    state: () => {
        return {
            token: '' || getToken()
        };
    },
    actions: {
        login(data: any) {
            //模拟接口请求返回数据
            return new Promise((resolve: (value: RootObject<LoginData>) => void, reject) => {
                login(data)
                    .then((res) => {
                        const token = res.data?.token;
                        if (token) {
                            //登陆成功
                            this.token = token;
                            setToken(token);
                            resolve(res);
                        } else {
                            // 抛出登陆失败的结果
                            reject({ err: res });
                        }
                    })
                    .catch((err) => {
                        //抛出接口异常
                        reject(err);
                    });
            });
        },
        logout() {
            return new Promise((resolve: (value: RootObject<LogoutData>) => void, reject) => {
                logout()
                    .then((res) => {
                        this.resetToken();
                        resolve(res);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        // 清除token以及一系列操作
        resetToken() {
            this.token = '';
            clearToken();
            //清除routers
            useAsyncRoutes().resetAllRoutes();
        }
    }
});
